package com.ben.utils.ext

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import com.ben.utils.log.Logger

/**
 * Author: bin.yang
 * Maintainer: bin.yang
 * Date: 2019/11/27
 * Copyright: 2019 Inc. All rights reserved.
 * Desc:
 */
fun Any.toActivity(context: Context?, intent: Intent?) = apply {
    tryCatch {
        context ?: return@tryCatch
        intent ?: return@tryCatch
        // 做下兼容
        if (context !is Activity) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)

        kotlin.runCatching {
            if (context is Activity) {
                // 过滤launcher本身界面，移除flag
                val info = context.applicationContext?.packageManager
                    ?.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY)?.activityInfo
                if (info?.packageName == context.packageName) {
                    intent.flags = 0
                }
            }
        }

        context.startActivity(intent)
    }
}

fun Any.toService(context: Context?, intent: Intent?) = apply {
    tryCatch {
        context ?: return@tryCatch
        intent ?: return@tryCatch
        context.startService(intent)
    }
}

fun Any.toReceiver(context: Context?, intent: Intent?) = apply {
    tryCatch {
        context ?: return@tryCatch
        intent ?: return@tryCatch
        context.sendBroadcast(intent)
    }
}

@SuppressWarnings("")
fun Bundle.debugShowBundleParams(tag: String = "DEBUG") {
    val mIterator = keySet().iterator()
    while (mIterator.hasNext()) {
        val mNext = mIterator.next()
        val o = get(mNext)
        o ?: continue
        Logger.d(tag, "showBundleParams key = $mNext,value = $o,class = ${o.javaClass}")
    }
}
